<template>
  <van-uploader v-model="fileList" :preview-image="false" :before-read="beforeRead" :after-read="afterRead" :deletable="false">
    <div :class="'upload_file ' + className">
      <div v-if="!imgUrl" class="upload_icon">
        <van-icon name="plus" /><br>
        <slot name="uploadName" />
      </div>
      <template v-else>
        <img :src="imgUrl" alt="" style="width: 100%;height: 100%;">
      </template>
    </div>
  </van-uploader>
</template>
<script>
import axios from 'axios';
import { getToken } from '@/lib/auth';
export default {
  props: {
    // 图片上传地址 - 完整地址
    action: {
      type: String,
      required: true
    },
    // 限制最小
    minSize: {
      type: [Number, String],
      required: false,
      default: 0
    },
    // 图片地址
    fileUrl: {
      type: String,
      required: false,
      default: ''
    },
    // 限制最大
    maxSize: {
      type: [Number, String],
      required: false,
      default: 100 * 1204
    },
    // 接受类型 .jpg,.png,.jpeg
    accept: {
      type: String,
      required: false,
      default: '.jpg,.png,.jpeg'
    },
    // 样式 - 需要外部定义
    className: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      fileList: [],
      tokenInfo: getToken(),
      // 图片显示地址
      imgUrl: ''
    };
  },
  watch: {
    fileUrl() {
      if (this.fileUrl) {
        this.imgUrl = this.fileUrl;
      }
    }
  },
  created() {
    this.imgUrl = this.fileUrl;
  },
  methods: {
    init(url) {
      this.imgUrl = url;
    },
    reset () {
      this.fileList = [];
      this.imgUrl = '';
    },
    // 文件读取验证
    beforeRead(file) {
      if (this.maxSize && file.size > this.maxSize * 1024) {
        this.handleMaxSizeError();
        return false;
      }
      if (this.minSize && file.size < this.minSize * 1024) {
        this.handleMinSizeError();
        return false;
      }
      var _imgType = file.name.split('.');
      _imgType = _imgType[_imgType.length - 1];
      _imgType = _imgType && _imgType.toLowerCase();
      if (this.accept.indexOf(_imgType) === -1) {
        this.handleFormatError();
        return false;
      }
      return true;
    },
    // 文件读取完成
    afterRead(file) {
      this.file = file.file;
      this.upload().then(res => {
        console.log(res);
        this.imgUrl = file.content;
        this.$emit('uploadSuccess', res);
      }, () => {
        this.$toast.fail(`上传失败！`);
      });
      this.imgUrl = file.content;
      console.log(file);
    },
    // 暴露在外面的上传
    upload() {
      return new Promise((resolve, reject) => {
        if (!this.file) {
          resolve('');
          return;
        }
        this.uploadFormData = new FormData();
        this.uploadFormData.append('formFile', this.file);
        this.uploadFile(this.action, this.uploadFormData).then(res => {
          console.log(res);
          if (res.status === 200) {
            resolve(res.data);
          } else {
            reject(res.data);
          }
        });
      });
    },
    // 请求
    uploadFile(url, data) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.tokenInfo
        }
      };
      return axios.post(url, data, config);
    },
    /* =======  错误提示  ====== */
    // 文件大小超出错误
    handleMaxSizeError() {
      this.$toast.fail(`文件太大，不能超过${this.maxSize}kb`);
    },
    handleMinSizeError() {
      this.$toast.fail(`文件太小，不能小于${this.minSize}kb`);
    },
    // 文件格式错误
    handleFormatError() {
      this.$toast.fail(`文件格式错误，请上传${this.accept}的图片`);
    }
    /* ==== end ==== */
  }
};
</script>
